package org.ourgrid.acceptance.util.aggregator;

import org.easymock.classextension.EasyMock;
import org.ourgrid.acceptance.util.AggregatorAcceptanceUtil;
import org.ourgrid.aggregator.AggregatorComponent;
import org.ourgrid.common.interfaces.control.AggregatorControl;
import org.ourgrid.common.interfaces.control.AggregatorControlClient;
import org.ourgrid.matchers.ControlOperationResultMatcher;

import br.edu.ufcg.lsd.commune.container.ObjectDeployment;
import br.edu.ufcg.lsd.commune.container.control.ModuleNotStartedException;
import br.edu.ufcg.lsd.commune.container.control.ModuleStoppedException;
import br.edu.ufcg.lsd.commune.container.logging.CommuneLogger;
import br.edu.ufcg.lsd.commune.context.ModuleContext;
import br.edu.ufcg.lsd.commune.testinfra.AcceptanceTestUtil;

public class Req_603_Util extends AggregatorAcceptanceUtil {

	public Req_603_Util(ModuleContext context) {
		super(context);
	}
	
	public void stopAggregatorWithWrongPublicKey(AggregatorComponent component, String wrongPublicKey) {
		stopAggregator(component, wrongPublicKey, true);
	}
	
	public void stopAggregator(AggregatorComponent component) {
		stopAggregator(component, null, true);
	}
	
	public void stopAggregatorNotStarted(AggregatorComponent component) {
		stopAggregator(component, null, false);
	}
	
	private void stopAggregator(AggregatorComponent component, String senderPublicKey, boolean
			isStarted) {
		CommuneLogger newLogger = EasyMock.createMock(CommuneLogger.class);
		component.setLogger(newLogger);
		
		AggregatorControl aggControl = getAggregatorControl(component);
		ObjectDeployment aggOD = getAggregatorDeployment(component);
		
		AggregatorControlClient aggClientMock = EasyMock.createMock(AggregatorControlClient.class);
			
		if (!isStarted) {
			if(aggControl == null) {
				aggClientMock.operationSucceed(
						ControlOperationResultMatcher.eqType(ModuleStoppedException.class));
			} else {
				if (senderPublicKey == null) {
					senderPublicKey = aggOD.getDeploymentID().getPublicKey();
				}	
				aggClientMock.operationSucceed(
						ControlOperationResultMatcher.eqCauseType("AggregatorComponent is not started.", ModuleNotStartedException.class));
			}
		}  else {
			if (senderPublicKey == null) {
				senderPublicKey = aggOD.getDeploymentID().getPublicKey();
				aggClientMock.operationSucceed(ControlOperationResultMatcher.noError());
			} else if(!aggOD.getDeploymentID().getPublicKey().equals(senderPublicKey)) {
				newLogger.warn("An unknown entity tried to stop the Aggregator. " +
						"Only the local modules can perform this operation. " +
						"Unknown entity public key: [" + senderPublicKey + "].");
			}
		}
		
		
		EasyMock.replay(newLogger);
		EasyMock.replay(aggClientMock);
	
		AcceptanceTestUtil.setExecutionContext(component, aggOD, senderPublicKey);
		aggControl.stop(false, false, aggClientMock);
		
		EasyMock.verify(aggClientMock);
		EasyMock.verify(newLogger);
		EasyMock.reset(newLogger);

	}

}
